import numpy as np
import csv
from datetime import datetime
from time import strftime


'''
Global and Local Empirical Bayes Smoothers with Gamma Model
'''

def getCurTime():
    """
    get current time
    Return value of the date string format(%Y-%m-%d %H:%M:%S)
    """
    format='%Y-%m-%d %H:%M:%S'
    sdate = None
    cdate = datetime.now()
    try:
        sdate = cdate.strftime(format)
    except:
        raise ValueError
    return sdate

def build_data_list(inputCSV):
    sKey = []
    fn = inputCSV
    f = open(inputCSV)
    #ra = csv.DictReader(file(fn), dialect="excel")
    ra = csv.DictReader(f, dialect="excel")
    
    for record in ra:
        #print record[ra.fieldnames[0]], type(record[ra.fieldnames[-1]])
        for item in ra.fieldnames:
            temp = int(float(record[item]))
            sKey.append(temp)
    sKey = np.array(sKey)
    sKey.shape=(-1,len(ra.fieldnames))
    return sKey



#--------------------------------------------------------------------------
#MAIN

if __name__ == "__main__":
    print '===================================================='
    print "begin at " + getCurTime()

    filepath = 'C:/_DATA/migration89_08/COUNTY Migration/clean/test/inflow_true_continental_id.csv'

    data = build_data_list(filepath)
    '''
    output = []
    for item in data:
        if int(item[1]) == 0:
            output.append(item)
    np.savetxt(filepath[:-4] + '_temp0.csv', output, delimiter=',', fmt = '%i')
    '''


    uniqueFlowDic = {}

    for item in data:
        tempStr = str(item[1])+'-'+str(item[2])
        if tempStr not in uniqueFlowDic:
            uniqueFlowDic[tempStr] = item[3]
        else:
            uniqueFlowDic[tempStr] += item[3]

    output = []
    for item in uniqueFlowDic:
        temp = item.split('-')
        output.append([int(temp[0]), int(temp[1]), uniqueFlowDic[item]])
                      




    np.savetxt(filepath[:-4] + '_allyear.csv', output, delimiter=',', fmt = '%i')
    